<template>
  <div>
    <swiper ref="mySwiper" :options="swiperOptions">
      <swiper-slide v-for="item in banner" :key="item.title">
        <img :src="item.image" alt="" width="100%" />
      </swiper-slide>
      <div class="swiper-pagination" slot="pagination"></div>
    </swiper>
    <!-- 轮播的图片按钮 -->
    <ul class="list">
      <li v-for="(item,index) in banner" :key="item.title" :class="{active: index===num}" @click="changeSwiper(index)" style="user-select:none;cursor:pointer">
        {{item.title}}
      </li>
    </ul>
  </div>
</template>

<script>
import api from '../../../api/index'
export default {
  name: 'VueSwiper',
  data() {
    const that = this
    return {
      num: 0,
      banner: [], // 轮播图数据
      arr: [1, 2, 3, 4, 5],
      // 轮播配置
      swiperOptions: {
        pagination: {
          el: '.swiper-pagination'
        },
        autoplay: {
          delay: 3000,
          stopOnLastSlide: false,
          disableOnInteraction: true
        },
        loop: true,
        on: {
          slideChangeTransitionStart: function() {
            // this.activeIndex 切换结束时，告诉我现在是第几个slide
            if (this.activeIndex === that.arr.length + 1) {
              that.num = 0
            } else {
              that.num = this.activeIndex - 1
            }
          }
        }
      }
    }
  },
  computed: {
    swiper() {
      return this.$refs.mySwiper.$swiper
    }
  },
  methods: {
    changeSwiper(index) {
      // 高亮选中
      this.num = index
      this.swiper.slideTo(index + 1, 1000, false)
    }
  },
  mounted() {
    api.getSwiper().then(res => {
      console.log('我是轮播图', res)
      this.banner = res.data.result
    })
  }
}
</script>
<style lang='less' scoped>
.list {
  display: flex;
  li {
    flex: 1;
    padding: 0.1rem;
    font-size: 0.24rem;
    line-height: 0.32rem;
    margin: 0.1rem;
    background: #eee;
    color: #666;
    text-align: center;
    display: flex;
    align-items: center;
  }
  .active {
    background: rgb(80, 116, 173);
    color: #fff;
  }
}
</style>
